package com.fh.shop.api.product.biz;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.common.SystemConstant;
import com.fh.shop.api.product.mapper.IProductMapper;
import com.fh.shop.api.product.po.Product;
import com.fh.shop.api.product.vo.ProductVo;
import com.fh.shop.api.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("productService")
public class IProductServiceImpl implements IProductService {
    @Autowired
    private IProductMapper productMapper;

    @Override
    public ServerResponse findList() {
        // 先从缓存中查
        String productListJson = RedisUtil.get("productList");
        // 缓存中存在，则直接放回
        if (StringUtils.isNotBlank(productListJson)) {
            List<ProductVo> productVos = JSON.parseArray(productListJson, ProductVo.class);
            return ServerResponse.success(productVos);
        }
        // 从数据库中查
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        // 在mp中查询指定的字段
        productQueryWrapper.select("id", "productname", "price", "mainImage");
        productQueryWrapper.eq("status", SystemConstant.IS_UP);
        productQueryWrapper.eq("recommend", SystemConstant.IS_RECOMMEND);
        productQueryWrapper.eq("newProduct", SystemConstant.IS_NEW_PRODUCT);
        List<Product> products = productMapper.selectList(productQueryWrapper);
        // po转vo
        List<ProductVo> productVoList = products.stream().map(x -> {
            ProductVo productVo = new ProductVo();
            productVo.setId(x.getId());
            productVo.setProductName(x.getProductName());
            productVo.setPrice(x.getPrice().toString());
            productVo.setMainImage(x.getMainImage());
            return productVo;
        }).collect(Collectors.toList());
        // 向缓存中放一份
        String productVoListJson = JSON.toJSONString(productVoList);
//        RedisUtil.set("productList", productVoListJson);
        RedisUtil.setEx("productList", productVoListJson, 60);
        // 响应给客户端
        return ServerResponse.success(productVoList);
    }
}
